//
//  AY_ReadChapterView.m
//  AiYue
//
//  Created by mac on 2023/10/25.
//

#import "AY_ReadChapterView.h"
#import "AY_ReadChapterCell.h"
#import "AY_BookDetailViewController.h"

#define AnimationDelay 0.3
@interface AY_ReadChapterView () <UITableViewDelegate,UITableViewDataSource,SXReadChapterCellDelegate>
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) UIView *contentView;
@property (nonatomic,strong) UIView *topView;

@property (nonatomic,strong) UIImageView *bookImg;
@property (nonatomic,strong) UILabel *bookName;
@property (nonatomic,strong) UILabel *chapterLab;
@property (nonatomic,strong) UILabel *author;
@property (nonatomic,strong) UIButton *sortBtn;
@end

@implementation AY_ReadChapterView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.hidden = YES;
        [self addSubview:self.contentView];
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(btnClicked)];
        [self addGestureRecognizer:tapGesture];
        [self.contentView addSubview:self.topView];
        [self.contentView addSubview:self.tableView];
    }
    return self;
}

- (void)goToDetail {
    AY_BookDetailViewController *bookDetailVC = [[AY_BookDetailViewController alloc] init];
    bookDetailVC.bookId = self.bookModel.bookId;
    [[AYTool viewControllerWith:self].navigationController pushViewController:bookDetailVC animated:YES];
}

- (void)setCurrentChapter:(NSInteger)currentChapter {
    _currentChapter = currentChapter;
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:currentChapter inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
    [self.tableView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.charpters.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ID = @"AY_ReadChapterCell";
    AY_ReadChapterCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[AY_ReadChapterCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    cell.delegate = self;
    cell.indexRow = indexPath.row;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    ReadChapterModel *model = self.charpters[indexPath.row];
    if (model.sortNo.integerValue == self.currentChapter + 1) {
        model.isRead = @"1";
    }else {
        model.isRead = @"0";
    }
    cell.model = model;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return YNUM(50);
}

- (void)didSelectCharpterWithIndex:(ReadChapterModel *)readChapterModel andChapterIndex:(NSInteger)index {
    if ([self.delegate respondsToSelector:@selector(didSelectCharpterWithIndex:andChapterIndex:)]) {
        [self.delegate didSelectCharpterWithIndex:readChapterModel andChapterIndex:readChapterModel.sortNo.integerValue - 1];
    }
}

- (void)setCharpters:(NSArray<ReadChapterModel *> *)charpters {
    _charpters = charpters;
    [self.tableView reloadData];
}

- (void)setColors {
    self.contentView.backgroundColor = COLOR([AYMMKV getStringForKey:ReadToolBackColor defaultValue:@"FEF6E9"]);
    self.chapterLab.textColor = COLOR([AYMMKV getStringForKey:ReadTitleColor defaultValue:@"422D10"]);
    self.bookName.textColor = COLOR([AYMMKV getStringForKey:ReadTitleColor defaultValue:@"422D10"]);
    self.author.textColor = COLOR([AYMMKV getStringForKey:ReadTitleColor defaultValue:@"422D10"]);
    [self.sortBtn setTitleColor:COLOR([AYMMKV getStringForKey:ReadTitleColor defaultValue:@"422D10"]) forState:UIControlStateNormal];
    [self.tableView reloadData];
}

- (void)setBookModel:(BookModel *)bookModel {
    _bookModel = bookModel;
    [self.bookImg sd_setImageWithURL:[NSURL URLWithString:bookModel.coverImg] placeholderImage:YImage(@"placeholderImage")];
    self.chapterLab.text = [NSString stringWithFormat:@"共%@章",bookModel.chapterNum];
    self.bookName.text = bookModel.title;
    self.author.text = bookModel.author;
}

#pragma mark - 排序
- (void)sortAction:(UIButton *)btn {
    if (!self.charpters || [self.charpters count] <= 0) {
        return;
    }
    btn.selected = !btn.selected;
    if (btn.selected) {
        [btn setTitle:@"  倒序" forState:UIControlStateNormal];
        self.charpters = [[self.charpters reverseObjectEnumerator] allObjects];
        [self.tableView reloadData];
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
    }else {
        [btn setTitle:@"  正序" forState:UIControlStateNormal];
        self.charpters = [[self.charpters reverseObjectEnumerator] allObjects];
        [self.tableView reloadData];
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
    }
}

- (void)btnClicked
{
    [self dismiss];
}

-(void)show
{
    UIView *view = [UIApplication sharedApplication].delegate.window;
    self.frame = view.bounds;
    self.backgroundColor = RGB(0, 0, 0, 0);
    self.hidden = NO;
    [UIView animateWithDuration:AnimationDelay animations:^{
        self.contentView.frame = CGRectMake(0, 0, self.contentView.width, SCREEN_H);
    } completion:^(BOOL finished) {
        self.backgroundColor = RGB(0, 0, 0, 0.6);
    }];
}

-(void)dismiss
{
    [UIView animateWithDuration:AnimationDelay animations:^{
        self.contentView.frame = CGRectMake(-SCREEN_W+100, 0, self.contentView.width, SCREEN_H);
    } completion:^(BOOL finished) {
        self.frame = CGRectMake(0, 0, -self.width, SCREEN_H);
        self.hidden = YES;
    }];
}

- (UIView *)topView {
    if (!_topView) {
        _topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.contentView.width, YNUM(169))];
        [self.contentView addSubview:_topView];
        self.bookImg = [AYTool createImageViewWithFrame:CGRectZero andImage:nil andBg:nil andRadius:YNUM(4) andAddSubView:_topView];
        [self.bookImg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_topView).offset(YNUM(20));
            make.top.equalTo(_topView).offset(GK_STATUSBAR_HEIGHT);
            make.width.mas_equalTo(YNUM(54));
            make.height.mas_equalTo(YNUM(68));
        }];
        
        self.chapterLab = [AYTool createLabelWithFrame:CGRectZero andText:nil andTextColor:COLOR([AYMMKV getStringForKey:ReadTitleColor defaultValue:@"422D10"]) andBgColor:nil andFont:YFont(14) andLines:1 andRadius:0 andAddSubView:_topView];
        [self.chapterLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.bookImg);
            make.top.equalTo(self.bookImg.mas_bottom).offset(YNUM(16));
        }];
        
        self.bookName = [AYTool createLabelWithFrame:CGRectZero andText:nil andTextColor:COLOR([AYMMKV getStringForKey:ReadTitleColor defaultValue:@"422D10"]) andBgColor:nil andFont:[UIFont boldSystemFontOfSize:YNUM(18)] andLines:2 andRadius:0 andAddSubView:_topView];
        [self.bookName mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.bookImg.mas_right).offset(YNUM(18));
            make.top.equalTo(self.bookImg).offset(YNUM(5));
            make.right.equalTo(self.contentView).offset(-YNUM(16));
        }];
        
        self.author = [AYTool createLabelWithFrame:CGRectZero andText:nil andTextColor:COLOR([AYMMKV getStringForKey:ReadTitleColor defaultValue:@"422D10"]) andBgColor:nil andFont:YFont(12) andLines:1 andRadius:0 andAddSubView:_topView];
        [self.author mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.bookImg.mas_right).offset(YNUM(18));
            make.top.equalTo(self.bookName.mas_bottom).offset(YNUM(5));
            make.right.equalTo(self.contentView).offset(-YNUM(16));
        }];
        
        self.sortBtn = [AYTool createButtonWithFrame:CGRectZero andTitle:@"  正序" andFont:YFont(14) andTitleColor:COLOR([AYMMKV getStringForKey:ReadTitleColor defaultValue:@"422D10"]) andBg:nil andImage:YImage(@"AY_sort") andBgImage:nil andTarget:self andAction:@selector(sortAction:) andRadius:0 andAddSubView:_topView];
        [self.sortBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.contentView).offset(-YNUM(20));
            make.centerY.equalTo(self.chapterLab);
        }];
        
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(goToDetail)];
        [_topView addGestureRecognizer:tap];
    }
    return _topView;
}

-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, YNUM(169), self.contentView.width, self.contentView.height - YNUM(169)) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.translatesAutoresizingMaskIntoConstraints = NO;
        _tableView.tableFooterView = [[UIView alloc] init];
    }
    return _tableView;
}

-(UIView *)contentView
{
    if (!_contentView) {
        _contentView = [[UIView alloc] initWithFrame:CGRectMake(-SCREEN_W+100, 0, SCREEN_W-100, SCREEN_H)];
        _contentView.backgroundColor = COLOR([AYMMKV getStringForKey:ReadToolBackColor defaultValue:@"FEF6E9"]);
    }
    return _contentView;
}
@end
